package com.woniuxy.cloud.batteryassembly.exception;

import com.woniuxy.cloud.demo.Result;
import com.woniuxy.cloud.exception.BatteryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 捕捉异常
 * 新增自定义异常请注释
 */
@RestControllerAdvice
@Slf4j
public class BatteryExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("出现异常", e);
        return new Result().setCode(500).setMsg(e.getMessage());
    }

    //捕获参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result ValidExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();

        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));

        log.error("出现异常",e.getBindingResult(),e.getParameter().getMethod());
        return new Result().setCode(655).setMsg("参数异常:"+message);
    }
    @ExceptionHandler(BatteryException.class)
    public Result batteryExceptionHandler(BatteryException e) {
        log.error("出现异常", e);
        return new Result().setCode(e.getCode()).setMsg(e.getMessage());
    }
}
